package com.tanger.common.websocket;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName: WebSocketServer
 * @Description:
 * @author Hchenbin
 * @date 2022年03月16日 下午5:48:05
 */
//@ServerEndpoint(value = "/socket/{pId}")
//@Component
public class WebSocketServer {

    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketServer.applicationContext = applicationContext;
    }

    /**
     * 当前在线连接数
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * 用来存放每个客户端对应的 WebSocketServer 对象
     */
    private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 接收 equipmentId
     */
    private String equipmentId = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("pId") String equipmentId) throws Exception{
        this.session = session;
        this.equipmentId = equipmentId;
        if (webSocketMap.containsKey(equipmentId)) {
            webSocketMap.remove(equipmentId);
            webSocketMap.put(equipmentId, this);
        } else {
            webSocketMap.put(equipmentId, this);
            addOnlineCount();
        }
        //注入bean
        //屏设备
        //xxxService = (XxxService) applicationContext.getBean(XxxService.class);
        log.info("设备连接:{},当前在线运行设备为:{}", equipmentId, getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose()  throws Exception {
        if (webSocketMap.containsKey(equipmentId)){
            webSocketMap.remove(equipmentId);
            subOnlineCount();
        }
        log.info("设备退出:{},当前在线设备为:", equipmentId, getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        if (!StringUtils.isEmpty(message)) {
            try {
                Map<String,String> map = session.getPathParameters();
                JSONObject putMsg = new JSONObject();
                putMsg.put("message",message);
                putMsg.put("fromEquipmentId", this.equipmentId);
                String toEquipmentId = equipmentId;
                if (!StringUtils.isEmpty(toEquipmentId) && webSocketMap.containsKey(toEquipmentId)) {
                    sendMessage(putMsg.toJSONString(), toEquipmentId);
                } else {
                    log.error("请求的 equipmentId:{}不在该服务器上", toEquipmentId);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("设备错误:{},原因:{}", this.equipmentId, error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public static void sendMessage(String message, String equipmentId) throws IOException ,EncodeException {
        if (!StringUtils.isEmpty(equipmentId) && !webSocketMap.containsKey(equipmentId)) {
            log.error("请求的 pId:{}不在该服务器上", equipmentId);
        } else {
            webSocketMap.get(equipmentId).session.getBasicRemote().sendText(message);
        }

    }


    public static synchronized AtomicInteger getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount.getAndIncrement();
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount.getAndDecrement();
    }
}
